<?php

namespace app\admin\controller;

use app\admin\controller\AcomController;
use think\Db;
use think\Model;
use think\Request;
use think\Image;

class AlbumController extends AcomController
{
    public function view(Request $request){
        $id = intval($request->id);
        $p = intval($request->get('page',1));
        $cover = Db::table('yu_album')->where('id',$id)->find();
        $field = '';
        $album = Db::table('yu_album_detail a')->field($field)->join('yu_file_infos f','f.id = a.f_id')->where('a.a_id',$id)->paginate('10',true,['type'=>'bootstrap','page'=>$p,'query' => ['id'=>$id]]);
        $list['list'] = $album;
        $list['page'] = $album->render();
        $list['id'] =$id;
        $this->assign('cover',$cover);
        $this->assign('list',$list);
        return view();
    }

    public function del($id){
        if(Db::table('yu_album_detail')->where('id', $id)->delete()){
            ajaxReturn('',1);
        }else{
            ajaxReturn();
        }
    }

    public function add(Request $request){
       $id = intval($request->id);
       $list = Db::table('yu_album')->where('status',1)->select();
       $this->assign('id',json_encode(['id'=>$id]));
       $this->assign('list',$list);
       return view();
    }

    public function save_detail(Request $request){
       $detail_id = $request->post('ids');

       $id = $request->post('id');
       if(!$detail_id){
          $this->error('请上传图片');
       }else{
           $detail_id = explode(',',$detail_id);
       }

        if(is_array($detail_id)){
            $data = [];
           foreach ($detail_id as $v){
               $data[] = array('a_id'=>$id,'f_id'=>$v , 'create_at' =>time());
           }
            $list = Db::table('yu_album_detail')->insertAll($data);
            if($list){
                $this->success('图片上传成功',url('admin/album/view',['id'=>$id]));
            }else{
                $this->error('未知错误');
            }
        }else{
             $this->error('未知错误') ;
        }
    }

    public function cover(){
        $cover_id = input('post.id/d');
        $album_id = input('post.album_id/d');
        $cover_url = Db::table('yu_file_infos')->field('thumb_path,file_name')->where('id',$cover_id)->find();
        $model = model('album');
        //$model->startTrans();
        $url=$cover_url['thumb_path'].$cover_url['file_name'];
        $re  = $model->where('id',$album_id)->setfield(['cover_id'=>$cover_id,'cover_url'=>"$url"]);
        Db::table('yu_album_detail')->where('is_cover',1)->setField('is_cover',0);
        $re3 = Db::table('yu_album_detail')->where('id',$cover_id)->setField('is_cover',1);
        if($re && $re3){
            $model->commit();
            ajaxReturn('',1);
        }else{
            $model->rollback();
            ajaxReturn();
        }
    }



}
